package com.poc.poc.controller;

import com.poc.poc.compoment.DistributedRedisLock;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DistributedRedisLock redisLock;

    @RequestMapping(path="/redis/test", method= RequestMethod.GET)
    public String RedisTest(){
        stringRedisTemplate.opsForValue().set("k1","v1");
        return stringRedisTemplate.opsForValue().get("k1");
    }

    @RequestMapping(path = "/redis/dislock", method = RequestMethod.GET)
    public String order(@RequestParam("prodId") String prodid) throws InterruptedException {

        if(redisLock.tryLock(prodid)){
            try{
                // redisLock.watchDog(prodid);
                TimeUnit.SECONDS.sleep(25);
                System.out.println("lock prod is ok");
                return "下单成功";
            }finally {
                redisLock.unLock(prodid, true);
            }
        }else {
            System.out.println("lock prod is failed");
            return "不能获取分布式锁，下单失败";
        }
    }


}
